package cn.xenosp.server.common.error;

import cn.dev33.satoken.exception.*;
import cn.hutool.core.date.DateUtil;
import cn.xenosp.server.common.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 项目名： service-web
 * 包路径： cn.xenosp.server.common.error
 * 作者：   TongHui
 * 创建时间: 2024-12-20 16:59
 * 描述: 全局异常处理
 * 版本: 1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalException {
    // 拦截：未登录异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public String handlerException(Exception ex, Model model) {
        log.info("===============全局异常处理==============");
        ex.printStackTrace();
        model.addAttribute("message",ex.getClass().getName() +"<br>"+ex.getMessage());
        if (ex instanceof NotLoginException){
            model.addAttribute("message",ex.getMessage());
            model.addAttribute("code", Constant.TOKEN_NULL);
            return "forward:/?message="+ex.getMessage();
        }
        if (ex instanceof NotPermissionException){
            NotPermissionException e = (NotPermissionException) ex;
            model.addAttribute("message","缺少权限：" + e.getPermission());
        }
        if (ex instanceof NotRoleException){
            NotRoleException e = (NotRoleException) ex;
            model.addAttribute("message","缺少角色：" + e.getRole());
        }
        if (ex instanceof NotSafeException){
            NotSafeException e = (NotSafeException) ex;
            model.addAttribute("message","二级认证校验失败：" + e.getService());
        }
        if (ex instanceof DisableServiceException){
            DisableServiceException e = (DisableServiceException) ex;
            model.addAttribute("message","当前账号 " + e.getService() + " 服务已被封禁 (level=" + e.getLevel() + ")：" + e.getDisableTime() + "秒后解封");
        }

        model.addAttribute("timestamp", DateUtil.now());
        model.addAttribute("exception",ex.getClass().getSimpleName());
        return "error/4xx.html";
    }
}
